from django.shortcuts import render_to_response
from django.template import RequestContext
from catalog.models import Edition
from django.core.paginator import Paginator

EDITIONS_PER_PAGE = 20

def edition_list(request):
    query = request.GET.get('query','')
    if query:
        editions = Edition.objects.all()
        for word in query.split():
            editions = editions.filter(title__icontains=word)
        count = editions.count()
        editions = editions.order_by('title')
        if count == 0:
            heading = u'No editions found matching "%s"' % query
        elif count == 1:
            heading = u'1 edition found'
        else:     
            heading = u'%s editions found - title order' % count
    else:
        count = Edition.objects.count()
        editions = Edition.objects.order_by('-meta_created')
        heading = u'Total: %s editions - recent additions first' % count
    page_num = request.GET.get('pg')
    qs = request.META['QUERY_STRING']
    page_fmt = '&pg=%s'
    if not page_num:
        page_num = 1
        qs += page_fmt%page_num
    else:
        page_num = int(page_num)
    next_qs = prev_qs = None
    page_qs = page_fmt%page_num
    page = Paginator(editions, EDITIONS_PER_PAGE, orphans=3).page(page_num)
    if page.has_next():
        next_qs = qs.replace(page_qs, page_fmt%page.next_page_number())
    if page.has_previous():
        prev_qs = qs.replace(page_qs, page_fmt%page.previous_page_number())
    isbn_list = ','.join(
        [edition.isbn for edition in page.object_list if edition.isbn])
    offset = (page_num-1) * EDITIONS_PER_PAGE
    return render_to_response('catalog/edition_list.html', locals(),
                              context_instance=RequestContext(request))
